package com.durian.base.update.proxy.impl

import android.content.Context
import com.durian.base.update.entity.DownloadEntity
import com.durian.base.update.entity.VersionEntity
import com.durian.base.update.proxy.IUpdateChecker
import com.durian.base.utils.AndroidInfoUtils
import com.durian.base.utils.FileUtils
import com.durian.base.utils.StringUtils
import java.io.File

open class DefaultUpdateChecker : IUpdateChecker {

    override fun doCheckVersionEntity(entity: VersionEntity): Boolean {
        val currentVersionCode = AndroidInfoUtils.versionCode()
        return entity.versionCode > currentVersionCode
    }

    override fun doCreateApkFile(context: Context, versionEntity: VersionEntity): File {
        val apkFileDir = createApkFileDir(context)
        if (!apkFileDir.exists()) {
            FileUtils.createDirFile(apkFileDir.absolutePath)
        }
        return createApkFile(context, apkFileDir, versionEntity)
    }

    override fun doCheckApkVerification(entity: DownloadEntity, downloadAfter: Boolean): Boolean {
        return if (downloadAfter) {
            if (StringUtils.isNotEmpty(entity.versionEntity.md5)) {
                FileInspector().inspect(entity) &&
                        ApkMd5Inspector().inspect(entity)
            }else{
                FileInspector().inspect(entity)
            }
        } else {
            if (StringUtils.isNotEmpty(entity.versionEntity.md5)){
                FileInspector().inspect(entity) &&
                        ApkMd5Inspector().inspect(entity)
            }else{
                false
            }
        }
    }

    /**
     * 缓存文件目录
     */
    open fun createApkFileDir(context: Context): File {
        return File(context.externalCacheDir, "XUpdateApkDir")
    }

    /**
     * 缓存文件路径
     */
    open fun createApkFile(context: Context, apkFileDir: File, versionEntity: VersionEntity): File {
        return File(apkFileDir, "${versionEntity.versionCode}.apk")
    }

}